package com.marktotop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.marktotop.entity.Admin;
import com.marktotop.entity.AdminRole;
import com.marktotop.entity.Menu;
import com.marktotop.entity.Role;
import com.marktotop.mapper.AdminMapper;
import com.marktotop.mapper.AdminRoleMapper;
import com.marktotop.mapper.RoleMapper;
import com.marktotop.response.ResultBean;
import com.marktotop.response.ResultCode;
import com.marktotop.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marktotop.service.ILoginLogService;
import com.marktotop.utils.AdminUtils;
import com.marktotop.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author marktotop
 * @since 2021-05-23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private ILoginLogService loginLogService;


    /**
     * 登录之后，添加登录日志，返回Token
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public ResultBean login(String username, String password,HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // 1.判断状态，用户信息为空
        if (null == userDetails){
            return ResultBean.result(ResultCode.LOGIN_USER_NOT_FOUND);
        }
        // 密码不匹配
        if (!passwordEncoder.matches(password,userDetails.getPassword())){

            return ResultBean.result(ResultCode.LOGIN_PASSWORD_ERROR);
        }
        // 账户锁定
        if (!userDetails.isEnabled()){
            return ResultBean.result(ResultCode.LOGIN_USER_NOT_ENABLE);
        }

        // 2.更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        // 3.返回Token
        String token = jwtTokenUtil.generateToken(userDetails);

        // 添加登录日志
        loginLogService.add(request);
        return ResultBean.ok().data("tokenHead",tokenHead).data("token",token);

    }

    /**
     * 根据登录名获取用户信息
     *
     * @param loginName 登录用户名
     * @return
     */
    @Override
    public Admin getProfileByUsername(String loginName) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",loginName).eq("enabled",true));
    }

    /**
     * 根据用户id查询对应的角色列表
     *
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    /**
     * 获取所有操作员
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    /**
     * 更新操作员角色 (先删后添加)
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public ResultBean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        Integer result = adminRoleMapper.addAdminRole(adminId, rids);
        if (rids.length==result){
            return ResultBean.ok().message("更新成功");
        }
        return ResultBean.error().message("更新失败");
    }

    /**
     * 更新当前登录管理员密码
     *      前端 判断旧密码与新密码是否一致，不允许重复修改
     *
     * @param adminId
     * @param oldPass
     * @param newPass
     * @return
     */
    @Override
    public ResultBean updateAdminPass(Integer adminId, String oldPass, String newPass) {
        // 先在数据库中查找对应用户信息
        Admin admin = adminMapper.selectById(adminId);
        // 旧密码与数据库相同！
        if (passwordEncoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(passwordEncoder.encode(newPass));
            // 将新密码存入数据库
            if (adminMapper.updateById(admin) == 1){
                return ResultBean.ok().message("当前登录管理员密码修改成功！");
            }
            return ResultBean.error().message("管理员密码修改操作失败！");
        } else {
            return ResultBean.error().message("旧密码与登录密码不相符！");
        }
    }

}
